#datatypes in rust
Explore tagged Tumblr posts
Text
youtube
0 notes
Text
i found some of the features of Rust a bit odd: the enums with types and values, the pattern-matching, the let statements. they are nice! but why did these seem like natural changes? i thought of the language as 'C++ with functional features and careful memory management', and the archetypical functional language for me is Scheme. Rust does not look like an interpolation of C and Scheme. recently, i've been learning Standard ML, and now i see where all of these features come from. an enum is just a datatype; the let statements are just the same as ML's; if let is just ML case ... of ...; there are probably more examples
these features seem less surprising after encountering them together in another context
10 notes
·
View notes
Text
This Week in Rust 518
Hello and welcome to another issue of This Week in Rust! Rust is a programming language empowering everyone to build reliable and efficient software. This is a weekly summary of its progress and community. Want something mentioned? Tag us at @ThisWeekInRust on Twitter or @ThisWeekinRust on mastodon.social, or send us a pull request. Want to get involved? We love contributions.
This Week in Rust is openly developed on GitHub and archives can be viewed at this-week-in-rust.org. If you find any errors in this week's issue, please submit a PR.
Updates from Rust Community
Project/Tooling Updates
Strobe Crate
System dependencies are hard (so we made them easier)
Observations/Thoughts
Trying to invent a better substring search algorithm
Improving Node.js with Rust-Wasm Library
Mixing C# and Rust - Interop
A fresh look on incremental zero copy serialization
Make the Rust compiler 5% faster with this one weird trick
Part 3: Rowing Afloat Datatype Boats
Recreating concurrent futures combinators in smol
Unpacking some Rust ergonomics: getting a single Result from an iterator of them
Idea: "Using Rust", a living document
Object Soup is Made of Indexes
Analyzing Data 180,000x Faster with Rust
Issue #10: Serving HTML
Rust vs C on an ATTiny85; an embedded war story
Rust Walkthroughs
Analyzing Data /,000x Faster with Rust
Fully Automated Releases for Rust Projects
Make your Rust code unit testable with dependency inversion
Nine Rules to Formally Validate Rust Algorithms with Dafny (Part 2): Lessons from Verifying the range-set-blaze Crate
[video] Let's write a message broker using QUIC - Broke But Quick Episode 1
[video] Publishing Messages over QUIC Streams!! - Broke But Quick episode 2
Miscellaneous
[video] Associated types in Iterator bounds
[video] Rust and the Age of High-Integrity Languages
[video] Implementing (part of) a BitTorrent client in Rust
Crate of the Week
This week's crate is cargo-show-asm, a cargo subcommand to show the optimized assembly of any function.
Thanks to Kornel for the suggestion!
Please submit your suggestions and votes for next week!
Call for Participation
Always wanted to contribute to open-source projects but did not know where to start? Every week we highlight some tasks from the Rust community for you to pick and get started!
Some of these tasks may also have mentors available, visit the task page for more information.
* Hyperswitch (Hacktoberfest)- [FEATURE] separate payments_session from payments core * Hyperswitch (Hacktoberfest)- [NMI] Use connector_response_reference_id as reference to merchant * Hyperswitch (Hacktoberfest)- [Airwallex] Use connector_response_reference_id as reference to merchant * Hyperswitch (Hacktoberfest)- [Worldline] Use connector_response_reference_id as reference to merchant * Ockam - Make ockam project delete (no args) interactive by asking the user to choose from a list of space and project names to delete (tuify) * Ockam - Validate CBOR structs according to the cddl schema for authenticator/direct/types * Ockam - Slim down the NodeManagerWorker for node / node status
If you are a Rust project owner and are looking for contributors, please submit tasks here.
Updates from the Rust Project
397 pull requests were merged in the last week
rewrite gdb pretty-printer registration
add FileCheck annotations to mir-opt tests
add MonoItems and Instance to stable_mir
add a csky-unknown-linux-gnuabiv2hf target
add a test showing failing closure signature inference in new solver
add new simpler and more explicit syntax for check-cfg
add stable Instance::body() and RustcInternal trait
automatically enable cross-crate inlining for small functions
avoid a track_errors by bubbling up most errors from check_well_formed
avoid having rustc_smir depend on rustc_interface or rustc_driver
coverage: emit mappings for unused functions without generating stubs
coverage: emit the filenames section before encoding per-function mappings
coverage: fix inconsistent handling of function signature spans
coverage: move most per-function coverage info into mir::Body
coverage: simplify the injection of coverage statements
disable missing_copy_implementations lint on non_exhaustive types
do not bold main message in --error-format=short
don't ICE when encountering unresolved regions in fully_resolve
don't compare host param by name
don't crash on empty match in the nonexhaustive_omitted_patterns lint
duplicate ~const bounds with a non-const one in effects desugaring
eliminate rustc_attrs::builtin::handle_errors in favor of emitting errors directly
fix a performance regression in obligation deduplication
fix implied outlives check for GAT in RPITIT
fix spans for removing .await on for expressions
fix suggestion for renamed coroutines feature
implement an internal lint encouraging use of Span::eq_ctxt
implement jump threading MIR opt
implement rustc part of RFC 3127 trim-paths
improve display of parallel jobs in rustdoc-gui tester script
initiate the inner usage of cfg_match (Compiler)
lint non_exhaustive_omitted_patterns by columns
location-insensitive polonius: consider a loan escaping if an SCC has member constraints applied only
make #[repr(Rust)] incompatible with other (non-modifier) representation hints like C and simd
make rustc_onunimplemented export path agnostic
mention into_iter on borrow errors suggestions when appropriate
mention the syntax for use on mod foo; if foo doesn't exist
panic when the global allocator tries to register a TLS destructor
point at assoc fn definition on type param divergence
preserve unicode escapes in format string literals when pretty-printing AST
properly account for self ty in method disambiguation suggestion
report unused_import for empty reexports even it is pub
special case iterator chain checks for suggestion
strict provenance unwind
suggest ; after bare match expression E0308
suggest constraining assoc types in more cases
suggest relaxing implicit type Assoc: Sized; bound
suggest removing redundant arguments in format!()
uplift movability and mutability, the simple way
miri: avoid a linear scan over the entire int_to_ptr_map on each deallocation
miri: fix rounding mode check in SSE4.1 round functions
miri: intptrcast: remove information about dead allocations
disable effects in libcore again
add #[track_caller] to Option::unwrap_or_else
specialize Bytes<R>::next when R is a BufReader
make TCP connect handle EINTR correctly
on Windows make read_dir error on the empty path
hashbrown: add low-level HashTable API
codegen_gcc: add support for NonNull function attribute
codegen_gcc: fix #[inline(always)] attribute and support unsigned comparison for signed integers
codegen_gcc: fix endianness
codegen_gcc: fix int types alignment
codegen_gcc: optimize popcount implementation
codegen_gcc: optimize u128/i128 popcounts further
cargo add: Preserve more comments
cargo remove: Preserve feature comments
cargo replace: Partial-version spec support
cargo: Provide next steps for bad -Z flag
cargo: Suggest cargo-search on bad commands
cargo: adjust -Zcheck-cfg for new rustc syntax and behavior
cargo: if there's a version in the lock file only use that exact version
cargo: make the precise field of a source an Enum
cargo: print environment variables for build script executions with -vv
cargo: warn about crate name's format when creating new crate
rustdoc: align stability badge to baseline instead of bottom
rustdoc: avoid allocating strings primitive link printing
clippy: map_identity: allow closure with type annotations
clippy: map_identity: recognize tuple identity function
clippy: add lint for struct field names
clippy: don't emit needless_pass_by_ref_mut if the variable is used in an unsafe block or function
clippy: make multiple_unsafe_ops_per_block ignore await desugaring
clippy: needless pass by ref mut closure non async fn
clippy: now declare_interior_mutable_const and borrow_interior_mutable_const respect the ignore-interior-mutability configuration entry
clippy: skip if_not_else lint for '!= 0'-style checks
clippy: suggest passing function instead of calling it in closure for option_if_let_else
clippy: warn missing_enforced_import_renames by default
rust-analyzer: generate descriptors for all unstable features
rust-analyzer: add command for only opening external docs and attempt to fix vscode-remote issue
rust-analyzer: add incorrect case diagnostics for module names
rust-analyzer: fix VS Code detection for Insiders version
rust-analyzer: import trait if needed for unqualify_method_call assist
rust-analyzer: pick a better name for variables introduced by replace_is_some_with_if_let_some
rust-analyzer: store binding mode for each instance of a binding independently
perf: add NES emulation runtime benchmark
Rust Compiler Performance Triage
Approved RFCs
Changes to Rust follow the Rust RFC (request for comments) process. These are the RFCs that were approved for implementation this week:
Add f16 and f128 float types
Unicode and escape codes in literals
Final Comment Period
Every week, the team announces the 'final comment period' for RFCs and key PRs which are reaching a decision. Express your opinions now.
RFCs
No RFCs entered Final Comment Period this week.
Tracking Issues & PRs
[disposition: merge] Consider alias bounds when computing liveness in NLL (but this time sound hopefully)
[disposition: close] regression: parameter type may not live long enough
[disposition: merge] Remove support for compiler plugins.
[disposition: merge] rustdoc: Document lack of object safety on affected traits
[disposition: merge] Stabilize Ratified RISC-V Target Features
[disposition: merge] Tracking Issue for const mem::discriminant
New and Updated RFCs
[new] eRFC: #[should_move] attribute for per-function opting out of Copy semantics
Call for Testing
An important step for RFC implementation is for people to experiment with the implementation and give feedback, especially before stabilization. The following RFCs would benefit from user testing before moving forward:
No RFCs issued a call for testing this week.
If you are a feature implementer and would like your RFC to appear on the above list, add the new call-for-testing label to your RFC along with a comment providing testing instructions and/or guidance on which aspect(s) of the feature need testing.
Upcoming Events
Rusty Events between 2023-10-25 - 2023-11-22 🦀
Virtual
2023-10-30 | Virtual (Melbourne, VIC, AU) | Rust Melbourne
(Hybrid - online & in person) October 2023 Rust Melbourne Meetup
2023-10-31 | Virtual (Europe / Africa) | Rust for Lunch
Rust Meet-up
2023-11-01 | Virtual (Cardiff, UK)| Rust and C++ Cardiff
ECS with Bevy Game Engine
2023-11-01 | Virtual (Indianapolis, IN, US) | Indy Rust
Indy.rs - with Social Distancing
2023-11-02 | Virtual (Charlottesville, NC, US) | Charlottesville Rust Meetup
Crafting Interpreters in Rust Collaboratively
2023-11-07 | Virtual (Berlin, DE) | OpenTechSchool Berlin
Rust Hack and Learn | Mirror
2023-11-07 | Virtual (Buffalo, NY, US) | Buffalo Rust Meetup
Buffalo Rust User Group, First Tuesdays
2023-11-09 | Virtual (Nuremberg, DE) | Rust Nuremberg
Rust Nürnberg online
2023-11-14 | Virtual (Dallas, TX, US) | Dallas Rust
Second Tuesday
2023-11-15 | Virtual (Cardiff, UK)| Rust and C++ Cardiff
Building Our Own Locks (Atomics & Locks Chapter 9)
2023-11-15 | Virtual (Richmond, VA, US) | Linux Plumbers Conference
Rust Microconference in LPC 2023 (Nov 13-16)
2023-11-15 | Virtual (Vancouver, BC, CA) | Vancouver Rust
Rust Study/Hack/Hang-out
2023-11-16 | Virtual (Charlottesville, NC, US) | Charlottesville Rust Meetup
Crafting Interpreters in Rust Collaboratively
2023-11-07 | Virtual (Berlin, DE) | OpenTechSchool Berlin
Rust Hack and Learn | Mirror
2023-11-21 | Virtual (Washington, DC, US) | Rust DC
Mid-month Rustful
Europe
2023-10-25 | Dublin, IE | Rust Dublin
Biome, web development tooling with Rust
2023-10-25 | Paris, FR | Rust Paris
Rust for the web - Paris meetup #61
2023-10-25 | Zagreb, HR | impl Zagreb for Rust
Rust Meetup 2023/10: Lunatic
2023-10-26 | Augsburg, DE | Rust - Modern Systems Programming in Leipzig
Augsburg Rust Meetup #3
2023-10-26 | Copenhagen, DK | Copenhagen Rust Community
Rust metup #41 sponsored by Factbird
2023-10-26 | Delft, NL | Rust Nederland
Rust at TU Delft
2023-10-26 | Lille, FR | Rust Lille
Rust Lille #4 at SFEIR
2022-10-30 | Stockholm, SE | Stockholm Rust
Rust Meetup @Aira + Netlight
2023-11-01 | Cologne, DE | Rust Cologne
Web-applications with axum: Hello CRUD!
2023-11-07 | Bratislava, SK | Bratislava Rust Meetup Group
Rust Meetup by Sonalake
2023-11-07 | Brussels, BE | Rust Aarhus
Rust Aarhus - Rust and Talk beginners edition
2023-11-07 | Lyon, FR | Rust Lyon
Rust Lyon Meetup #7
2023-11-09 | Barcelona, ES | BcnRust
11th BcnRust Meetup
2023-11-09 | Reading, UK | Reading Rust Workshop
Reading Rust Meetup at Browns
2023-11-21 | Augsburg, DE | Rust - Modern Systems Programming in Leipzig
GPU processing in Rust
2023-11-23 | Biel/Bienne, CH | Rust Bern
Rust Talks Bern @ Biel: Embedded Edition
North America
2023-10-25 | Austin, TX, US | Rust ATX
Rust Lunch - Fareground
2023-10-25 | Chicago, IL, US | Deep Dish Rust
Rust Happy Hour
2023-11-01 | Brookline, MA, US | Boston Rust Meetup
Boston Common Rust Lunch
2023-11-08 | Boulder, CO, US | Boulder Rust Meetup
Let's make a Discord bot!
2023-11-14 | New York, NY, US | Rust NYC
Rust NYC Monthly Mixer: Share, Show, & Tell! 🦀
2023-11-14 | Seattle, WA, US | Cap Hill Rust Coding/Hacking/Learning
Rusty Coding/Hacking/Learning Night
2023-11-15 | Richmond, VA, US + Virtual | Linux Plumbers Conference
Rust Microconference in LPC 2023 (Nov 13-16)
2023-11-16 | Nashville, TN, US | Music City Rust Developers
Python loves Rust!
2023-11-16 | Seattle, WA, US | Seattle Rust User Group
Seattle Rust User Group Meetup
2023-11-21 | San Francisco, CA, US | San Francisco Rust Study Group
Rust Hacking in Person
2023-11-22 | Austin, TX, US | Rust ATX
Rust Lunch - Fareground
Oceania
2023-10-26 | Brisbane, QLD, AU | Rust Brisbane
October Meetup
2023-10-30 | Melbourne, VIC, AU + Virtual | Rust Melbourne
(Hybrid - in person & online) October 2023 Rust Melbourne Meetup
2023-11-21 | Christchurch, NZ | Christchurch Rust Meetup Group
Christchurch Rust meetup meeting
If you are running a Rust event please add it to the calendar to get it mentioned here. Please remember to add a link to the event too. Email the Rust Community Team for access.
Jobs
Please see the latest Who's Hiring thread on r/rust
Quote of the Week
When your Rust build times get slower after adding some procedural macros:
We call that the syn tax :ferris:
– Janet on Fosstodon
Thanks to Jacob Pratt for the suggestion!
Please submit quotes and vote for next week!
This Week in Rust is edited by: nellshamrell, llogiq, cdmistman, ericseppanen, extrawurst, andrewpollack, U007D, kolharsam, joelmarcey, mariannegoldin, bennyvasquez.
Email list hosting is sponsored by The Rust Foundation
Discuss on r/rust
9 notes
·
View notes
Text
#and you CAN write memory-unsafe rust code; it just has to be within an “unsafe” block#so you DO have access to some C-like constructs if you Really Need to do smth like that#maybe thats useful for the linux kernel or w/e but i certainly havent needed to use it. rust's normal stuff works just fine
just expanding on this, it being in a separate block means that if anything fucks up then theres only a small area of code to search for. if you get a segfault in C, then any bit of code could do that. if you get a segfault in rust then only* unsafe code can do that. unsafe can also be used when you as the programmer knows something the compiler doesnt.
basic rust:
rust makes sure that in "safe" rust if some data can mutate, there can only be one consumer at a time. you dont want x to change while something else prints x. you dont want race conditions.
rust also deals with mutability. by default it is not possible to mutate some data, you have to mark it as mutable. and again, you cannot have multiple mutable references to the same data.
slices. in rust a slice is a datatype that is effectively an array. a continuous block of data. an array is of fixed size, a vec can grow and shrink, and a slice is generic and works with both of them.
the unsafe code part:
... sometimes this "one mutable reference per bit of data" is overly restrictive! lets say you have some slice, and you want to split it in two. uhhh i dont know, lets say its sorted and you want to split it into two arrays for negatives and positives/zeros, and you want both of these two new arrays to be mutable. well if we design a function to split arr in two, it would need to return (&mut [T], &mut [T]). two separate mutable slices. but the data is owned by one variable. we know we can split this variable up, but the compiler doesnt! it just sees lots of data owned by one variable!
so any function splitting into multiple mutable parts needs unsafe code to get around this!
this example was taken from the book.
*although it would be great if segfaults were guaranteed to be only in unsafe code, im not sure it would be possible to *guarantee* this. the compiler devs are human and mistakes sometimes slip through. e.g. cve-rs was a fun project that allowed for so much bullshit, but the bug it exploited has been patched.
what the devs can guarantee, however, is that you wont get segfaults in safe code unless you specifically look for them. if youre just writing code and not trying to get a segfault, you wont get segfaults in safe code.
also when i say segfaults i mean them and a whole host of other memory corruption errors. use after frees, double frees, etc.
If any Haskell and or Rust fans follow me, give me 1 good reason to learn them
#i speak i ramble#rust#i tried making this accessible to people who dont know rust. but because its all about ownership its probably a bit difficult.#to me understanding this was great for my intuition about ownership and the borrow checker by and large#also you need to write unsafe code to implement IterMut by hand most of the time#for *exactly the same reason*#anyways stickia404 if youve got a project you wanna write in rust then learn rust!#its such a good language!#and guess what. so is haskell!#i have yet to find a language as readable as hask. i have yet to find a language as fun to work in as rust.#both languages are great! if you pick either of them you cannot go wrong.#please please please feel free to ask *anything*. if its rust i will be able to help. if its hask i will only probably be able to help.
33 notes
·
View notes
Note
What is Haskell used for? I can point to many languages and say, "oh, this is often used for thus and such" but I don't know what Haskell's common use cases are.
The main use of Haskell is in improving Haskell :P
Seriously, parser combinators are a great idea and easily expressed in Haskell, and so it's easy enough to write some basic parsers for a non-syntax heavy language, and a lot of the features are developed with this in mind (and has trickle down effects on serialization/deserialization libraries--Aeson is pretty good for dealing with JSON (de)serialization)
I really like it for writing backends with Servant (kind of like Flask in that it's not a batteries-included type of server library), although the errors are kind of confusing, especially if you're not used to Haskell already
There's a relatively Haskell-specific development of a thing called "monad transformers", which is an ugly term for a way to write capability-specific abstractions
For instance, if you have MonadDatabase or a DatabaseT in your type signature, then that function can call whatever functions are defined for MonadDatabase, be it get/set for some restricted types, or computing raw SQL...either way, it's obvious that if you're trying to use this to get the system time, you're using the wrong abstraction (and you can have multiple of these in your type signature, so you might have (Monad m) => AWSBucketT (TimeT (m Int)), which assuming some definitions, might say "In some monad m, I'll return an Int, and have capabilities to access our company's AWSBuckets and read the system time"
(Monad transformers as they're used often aren't great imo, but i've already gone too deep, perhaps too deep by even saying "monad")
Beyond that, a couple other useful things: you might know map from Python or Rust, but what if it was easier to automatically get a sensible definition of map? After all, there's usually only one "right answer"--apply the function to all relevant targets!
So say you have some type like data Tree e a = Leaf e | Node a [Tree e a]
(so, a Tree over e and a is either a `Leaf` that only has an `e`, or a Node, which is annotated with an `a`, and has a list of child trees over the same types)
then if you just add `derive Functor` to the end of the datatype, it'll create a map function that looks like:
map f (Leaf e) = Leaf e
map f (Node a trees) = Node (f a) [map f tree | tree <- trees]
(or in pythonish: def map(f, t): if t.isLeaf(): pass; else: t.value = f(t.value); t.children = [map(f, tree) for tree in t.children])
Say you want your map to effect the Leafs rather than the annotations of the Nodes, then all you need to do is flip the type variables, then you can just write it as data Tree a e = Leaf e | Node a [Tree a e] deriving Functor
There's similar derivings for Show (the default printing type) or JSON de/serialization among others. If you're familiar with Rust's derive macro, it's a similar thing
This isn't something one should choose a language *for* but i think it's pretty neat
Property testing is easy in Haskell, you assert some property that you think your funciton should have (say, f(f(x)) = f(x)), write a way to compare the output for equality (or derive it), write a way to generate your inputs (or derive it, you can also easily customise it thanks to the combinators), and then your computer will generate however many "unit tests" that you want, and then check them all at once against the property. (There's an extension to this where if you put an ordering of "complexity", the property testing library will often try to find the "simplest" (according to your definition) input that violates the property.)
The pattern matching/equational definition of functions is something that I like a lot, there's a case analyzer built into the compiler that tells you when you've neglected a case (or added a case to a datatype), and there's extensions for IDEs that will show this as a linting message
Some other things that Haskell's used for is HPC (supposedly the FFI isn't awful, and implementing a really basic version of Map/Reduce in Haskell is pretty trivial, thanks to the thought put into async + threaded programming (it has problems and footguns, just mostly different ones than you're used to except for "the fuck is the runtime doing"; that just happens, and the GHC RTS i hear is like an abyss of phd theses)
There's also a healthy niche of circuit design(?), thanks to the deep support for embedded dsls; I'd recommend going through https://hackage.haskell.org/package/clash-ghc or Conal Elliot's work
Finally, Haskell is a language that tries to be on the forefront of language design. This means that a lot of useless and confusing features have snuck into the language, although usually they're gatekept behind compiler extensions. However, a lot of neat things show up early on in the Haskell world, before a lot of other programming languages pick up the features! I've already mentioned the deriving feature similar to Rust, it also has a linear types extension (tho support is limited as its a recent addition), and was a breeding ground for reactive programming iirc (React makes a lot more sense than Haskell's similar libraries tho)
#long post#trying not to be too technical while also being correct#i'm bad at selling haskell because it just feels so much comfier to me than any other language for a bunch of reasons that seem minor#but stack up#capability based programming good#equational function defintions good#the freedom of expression while also being constrained to reasonableness is good#definitely rambling
12 notes
·
View notes
Link
Dapper Labs, pasukan di belakang CryptoKitties dan Flow Blockchain, telah mendedahkan kerjasama dengan projek Libra, stablecoin Facebook untuk berkongsi teknologi proprietari. CTO Dapper Labs, Dieter Shirley mendedahkan bahawa blockchain Dapper Flow akan menggunakan teknologi Libra Move sebagai mesin maya (VM), sementara Libra akan menggunakan bahasa pengaturcaraan kontrak pintar Dapper Cadence dalam kerjasama perkongsian teknologi. Shirley menyatakan bahawa Flow akan mendapat keuntungan dari kecekapan prestasi Move, sementara Libra mendapat keuntungan dari reka bentuk mesra pemaju Cadence. Dapper Labs telah membangunkan Cadence selama kira-kira satu tahun sebelum melancarkan Bahasa pengaturcaraan tersebut di platform percubaan pembangun perisian. Bahasa pengaturcaraan ini dirancang untuk mempermudahkan penggunaan dan prestasi optimum untuk kontrak pintar dan berdasarkan teori linear. Dieter menyatakan bahawa pasukan Move “adalah satu-satunya blockchain pengeluaran lain yang sebenarnya menggabungkan idea-idea ini yang diambil dari teori linear dan menerapkannya dalam konteks kontrak pintar,” sambil menambah: “Move adalah bahasa pengaturcaraan berorientasikan sumber, tetapi direka bentuk untuk prestasi dan tidak mudah untuk dibaca dan digunakan. Cadence, sebaliknya, dirancang untuk penggunaan, dengan sintaks yang diilhamkan oleh Swift dan Rust. “ Shirley mengatakan bahawa Move dan Cadence adalah “saling menyokong antara satu sama lain.” Dia menggambarkan Move sebagai “VM yang sangat berprestasi dari semua arah” yang “sangat mementingkan kecekapan, kelajuan, dan pengeluaran hasil,” sementara Cadence dibangun “dari atas ke bawah” dengan “fokus pada kemudahan untuk digunakan oleh pemaju perisian”. Rujukan: https://cointelegraph.com/news/dapper-labs-announces-tech-sharing-partnership-with-libra === Jika anda mahu berdiskusi dan bertanya tentang bitcoin, matawang kripto (cryptocurrency) dan teknologi blockchain di Malaysia. Anda dijemput bersama-sama komuniti Bitcoin Malaya di FB dan @CoinDotMy di Telegram. Jangan lupa ikuti kami di Twitter dan Instagram! Nak beli bitcoin? Jangan tertipu dengan scammer bitcoin! Biar faham dulu tentang bitcoin! Klik sini untuk belajar. (function () { function appendFbScript() { var js, id = 'facebook-jssdk', fjs = document.getElementsByTagName('script')[0]; if (document.getElementById(id)) return; js = document.createElement('script'); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js#xfbml=1&appId=623358408023673&version=v2.0"; fjs.parentNode.insertBefore(js, fjs); window.fbAsyncInit = function () { FB.init({ appId: '623358408023673', xfbml: true, version: 'v2.0' }); FB.Event.subscribe('comment.create', function (comment_data) { console.log(comment_data); update_comments_count(); }); FB.Event.subscribe('comment.remove', function (comment_data) { update_comments_count(); }); function update_comments_count(comment_data, comment_action) { jQuery.ajax({ type: 'GET', dataType: 'json', url: 'https://coin.my/wp-admin/admin-ajax.php', data: { action: 'clear_better_facebook_comments', post_id: '57140' }, success: function (data) { // todo sync comments count here! data have the counts }, error: function (i, b) { // todo } } ) }; }; jQuery(document).on("ajaxified-comments-loaded",appendFbScript); } appendFbScript(); })(); window.fbAsyncInit = function() { FB.init({ appId : '623358408023673', xfbml : true, version : 'v2.12' }); FB.AppEvents.logPageView(); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); !function(f,b,e,v,n,t,s) {if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)}; if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t,s)}(window, document,'script', 'https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '2898906260162341'); fbq('track', 'PageView'); HEROKITA.com | Digital Talents On Demand Source link
0 notes
Link
Rust is a language which I have been looking into lately and starting with this post I will begin a new series of articles to share what I have learned so far to help other beginners or those interested in getting to know rust get to grips with the language.
So what is rust? Well, the rust wikipedia page states it quite well:
Rust is a multi-paradigm programming language focused on performance and safety, especially safe concurrency. Rust is syntactically similar to C++, but provides memory safety without using garbage collection. Rust was originally designed by Graydon Hoare at Mozilla Research, with contributions from Dave Herman, Brendan Eich, and others.
Source: Rust Wikipedia Page
Getting setup
To get setup go to the installation page of the official rust language site. Follow the instructions for your operating system of choice and once you've installed everything you should be able to run rustc --version in your terminal and get something like this in response:
rustc 1.39.0-nightly (eb48d6bde 2019-09-12)
If that command ran correctly without any errors, the setup stage is over and we are ready to get coding!
Hello world!
Let's make a file called Hello.rs and write the following inside the file:
fn main() { println!("Hello world!"); }
The main() function is a required function in rust, it is the function executed when a programme is run. println!() is a macro function (we will look into that concept in a future article) which is roughly equivilent to echo in PHP, System.Console.WriteLine() in C# and console.log() in JavaScript and it's one job like these others is to write content to the terminal/console.
Sidenote 1:
As a heads up, println!() works with values other than strings a bit differently, for example if we wanted to print a number to the terminal we would have to write println!("{}", 2); which basically tells the println!() macro to write a string where the placeholder {} is the value 2.
We can output multiple values this way too, for example println!("{}, {}", 1, 2); will output "1, 2".
We can name our values by index too, for example println!("{1}, {0}", 1, 2); will output "2, 1".
There is also the special debug placeholder println!("{:?}", vec![1, 2, 3]); for vectors, structs, etc. This example would output [1, 2, 3] for reference but don't worry about datatypes just yet, we will look at them in detail in an upcoming article.
Moving back on track, we can go to our terminal and compile our Hello.rs file using the rustc Hello.rs command to tell the rust compiler (rustc) to compile the Hello.rs file. This will output 2 new files names Hello.pdb and Hello.exe.
Sidenote 2:
We can ignore the .pdb file as this is just a programme database file which the .exe file uses to lookup debugging information. Here is a wiki page with more information on .pdb files
To run our application we can now simple type ./Hello into the terminal to run the Hello.exe file and you should see it output the text "Hello world" in the terminal!
Conclusions
Rust can seem like a daunting language that is hard to learn and quite frankly it is at times but we have all had this feeling as we begin to journey into a new language, stack or role and so let us not be daunted when challenged to learn!
I hope this article has brought you some value and has given you a nice first step into getting setup, writing, compiling and executing with rust. See you in the next one.
0 notes
Text
What are Variables in Programming?
Check this out https://bizanosa.com/fc/what-are-variables/
What are Variables in Programming?
What are Variables in programming ?
A variable is a reference to some information. This could be information you may need to use later on in your program .
For instance, assume you want to store two values 1001 and 12020 in your program so that later on you may use these values. The way that you will achieve this is by using variables.
The steps involved in storing and later using these values include:
Create the variables with appropriate identifiers (names).
Store your values of 1001 and 12020 in those two variables you’ve created . This is called assigning a value to a variable.
Retrieve and use the stored values from the variables.
Note that with variables you can change the values they store. For instance if you no longer need 1001 and 12020, you will just assign new values to your stored variable names.
Unlike constants in most programming languages, variables are changeable values.
A variable must have an identifier. Some programming languages are statically typed while others are dynamically typed. This is in reference to the data type the programming language can hold and execute in the variable once it is declared.
Statically typed
In strict programming languages such as C++ and Java, you must declare your variables before you can use them.In these programming languages once you declare a variable you cannot change the data type it can hold. For instance once you declare a variable as an integer, it can not be used to hold a string or a character because an integer is a number value. This is called static typing . These are statically typed programming languages.
Examples of statically typed programming languages: Java, C, C++, Haskell, Scala, Kotlin , COBOL,Ada, Rust, Pascal, C# etc .
Dynamically Typed programming languages
In dynamic typing , data types of your variables can be changed at run time. If you declare a variable as a number. Later on you could store a different data type in that variable and your program would still execute without any run time errors.
Certain programs such as Javascript, allows you to use a variable even before it has been declared. However in ecmascript 2015, there are limitations to this depending on the keyword definitions you use for defining your variables,
Examples of dynamically typed programming languages: Ruby, Javascript, Python, PHP, Clojure, erlang ,Lisp, Perl etc .
Examples of Variable declarations
Variable declaration in C
The following are some of the Variable data types in C . You need to use the correct one to declare your variable .For example if you want to store absolute negative or positive digits with no decimals you may use int .
Type Description char Typically a single octet(one byte). int Integer value float A single-precision floating point value. double A double-precision floating point value. void Represents the absence of type.
How to declare variables in C – The syntax
data-type variable-identifier;
eg :
int tax;
If you want to declare a list of variables :
data-type variable-identifier0,variable-identifier1,variable-identifier2;
float price, profit,cost;
Initializing a variable in C :
Initializing a variable means , giving it an initial value when it is declared.
int tax = 16;
float price=199.99, profit= 57.2, cost;
Variable declaration in C++
Here is the complete list of fundamental types in C++:
Group Type names* Notes on size / precision Character types char Exactly one byte in size. At least 8 bits. char16_t Not smaller than char. At least 16 bits. char32_t Not smaller than char16_t. At least 32 bits. wchar_t Can represent the largest supported character set. Integer types (signed) signed char Same size as char. At least 8 bits. signed short int Not smaller than char. At least 16 bits. signed int Not smaller than short. At least 16 bits. signed long int Not smaller than int. At least 32 bits. signed long long int Not smaller than long. At least 64 bits. Integer types (unsigned) unsigned char (same size as their signed counterparts) unsigned short int unsigned int unsigned long int unsigned long long int Floating-point types float double Precision not less than float long double Precision not less than double Boolean type bool Void type void no storage Null pointer decltype(nullptr)
Source : http://www.cplusplus.com/doc/tutorial/variables/
How to declare variables in C++ – The syntax
C++ is a direct child of the C programming language. This means that variable declaration in C++ is just like it is in C.
data-type variable-identifier;
eg :
int tax;
If you want to declare a list of variables :
data-type variable-identifier0,variable-identifier1,variable-identifier2;
float price, profit,cost;
Initializing a variable in C :
Initializing a variable means , giving it an initial value when it is declared.
int tax = 16;
float price=199.99, profit= 57.2, cost;
Example code in CPP:
CPP code to calculate Gross profit per unit
// operating with variables #include <iostream> using namespace std; int main () // declaring variables: float cost, sellingPrice, profit; // process and initialization: cost = 55.50; sellingPrice = 119.99; profit = sellingPrice - cost ; // print out the result: cout << "The profit is : " << profit; // end program: return 0;
To run the above code, copy it and paste it here : http://cpp.sh
Read More about CPP variables .
Variable declaration in C#
Things to note : – variables can be declared with or without modifiers. A modifier defines the scope of a variable, i.e. is it a public variable or a private variable. You will use these access modifiers to secure your variables appropriately. – Variables defined without a modifier are only available within the methods in which they are defined. (Instance variables)
How to declare variables in C# – The syntax
Variable with a modifier
modifier dataType variableIdentifier;
example:
/*...public variable declaration...*/ private float cost, sellingPrice; /*...private variable declaration...*/ public float profit;
Assign initial value to variable
modifier dataType variableIdentifier = value;
Example:
/*...public variable declaration...*/ private float cost = 99.99, sellingPrice = 199.90;
Variable without a modifier
type variableName = value; // Usable and accessible within a method / object .
Example :
int age = 5;
Read more about types and variables .
Variable declaration in java
The following are acceptable and valid Java variables declaration
int x, y, z; // Declares three integers int x = 10, y = 10; // Example of variable initialization in Java byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char c = 'c'; // the char variable a is initialized with value 'c'
Variable declaration in Python
The following is valid code with variables in python
sales = 235 # An integer assignment sellingPrice = 99.90 # A floating point variable product = "Microphone" # A string variable assignment revenue = sellingPrice * sales # calculates revenue from the given variables # The Output via print print sales # outputs 235 print revenue # prints total revenue print product # Outputs Microphone
You can run the above code in ideone
Variable declaration in Javascript
Watch this video on YouTube
Variable declaration in PHP
Points to note about PHP variables
Variables are denoted with a leading dollar sign ($) e.g. $profit, $loss , $sellingPrice.
The variable value is its most recent assigned value.
Variables are assigned with the = operator, i.e. $profit = 20; .
Variables can be declared before assignment or not.
Variables in PHP are dynamic. refer up there for dynamically typed programming languages.
The following code is taken from the php manual here . It shows a sample of variable code in PHP
<?php class foo var $bar = 'I am bar.'; var $arr = array('I am A.', 'I am B.', 'I am C.'); var $r = 'I am r.'; $foo = new foo(); $bar = 'bar'; $baz = array('foo', 'bar', 'baz', 'quux'); echo $foo->$bar . "\n"; echo $foo->$baz[1] . "\n"; $start = 'b'; $end = 'ar'; echo $foo->$start . $end . "\n"; $arr = 'arr'; echo $foo->$arr[1] . "\n"; ?>
To learn more about Programming, click the button below.
Join the FULL Intro to Programming Here >>
0 notes
Text
notarealwelder wrote
yeah, all these things are just algebraic datatypes ADTs are Neat
cauchesque
adts are imo #1 reason to do rust
so that's what they are called! yes, i'm really enjoying them in ML (they feel like cheating)
i found some of the features of Rust a bit odd: the enums with types and values, the pattern-matching, the let statements. they are nice! but why did these seem like natural changes? i thought of the language as 'C++ with functional features and careful memory management', and the archetypical functional language for me is Scheme. Rust does not look like an interpolation of C and Scheme. recently, i've been learning Standard ML, and now i see where all of these features come from. an enum is just a datatype; the let statements are just the same as ML's; if let is just ML case ... of ...; there are probably more examples
these features seem less surprising after encountering them together in another context
10 notes
·
View notes